import { Component, OnInit } from '@angular/core';
import { NetService } from './../../services/net.service';
import { NzMessageService } from 'ng-zorro-antd';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';
@Component({
  selector: 'app-meta-list',
  templateUrl: './meta-list.component.html',
  styleUrls: ['./meta-list.component.scss']
})
export class MetaListComponent implements OnInit {
  public dataSet = [];
  public headers = ['分组', '权限', '角色', '操作'];
  public roles = [];
  public metaGroupCheck: string;
  public metaGroup = [];
  public modalVisible = false;
  public metaForm: FormGroup;
  constructor(
    private net: NetService,
    private nzmsg: NzMessageService,
    private fb: FormBuilder
  ) {
    this.getMetaList();
    this.getRoleList();
  }
  async changeMeta(meta, role, e) {
    if (e) {
      meta.roles.push(role.code);
    } else {
      meta.roles = meta.roles.filter(item => item !== role.code);
    }
    const result = await this.net.put('/api/metas', meta);
    if (result) {
      this.nzmsg.success('修改权限成功!');
    }
  }
  // 列表过滤，改变分组
  changeGroup(data) {
    this.metaGroupCheck = data;
    this.getMetaList();
  }

  async getMetaList() {
    const cond = [];
    if (this.metaGroupCheck) {
      cond.push(`group=${this.metaGroupCheck}`);
    }
    const result = await this.net.get(`/api/metas?${cond.join('&')}`);
    if (result) {
      this.dataSet = this.handleData(result['data']);
      if (cond.length === 0) {
        const metaGroup = {};
        this.dataSet.forEach(item => {
          metaGroup[item.group] = {
            label: item.group_des,
            value: item.group
          };
        });
        this.metaGroup = Object.values(metaGroup);
      }
    }
  }
  async getRoleList() {
    const result = await this.net.get('/api/roles');
    if (result) {
      this.roles = this.handleData(result['data']);
    }
  }

  async delMeta(item) {
    const result = await this.net.delete(`/api/metas/${item._id}`);
    if (result) {
      this.nzmsg.success('删除权限成功！');
      this.getMetaList();
    }
  }

  // 数据格式转换
  handleData(data) {
    let group = [];
    const groupData = {};
    data.forEach(item => {
      const fid = group.includes(item.resource);
      if (!fid) {
        groupData[item.resource] = [item];
        group.push(item.resource);
      } else {
        groupData[item.resource].push(item);
      }
    });
    group = [];
    Object.keys(groupData).forEach(item => {
      group.push(...groupData[item]);
    });
    return group;
  }
  transRoleToForm(roles) {
    const arr = [];
    roles.forEach(item => {
      const obj = {};
      obj['label'] = item.name;
      obj['value'] = item.code;
      obj['checked'] = false;
      arr.push(obj);
    });
    return arr;
  }

  addMeta() {
    console.log(this.transRoleToForm(this.roles));
    this.metaForm.reset({
      group: null,
      group_des: null,
      permission: null,
      permission_des: null,
      roles: this.transRoleToForm(this.roles)
    });
    this.modalVisible = true;
  }

  modalCancel() {
    this.modalVisible = false;
  }
  modalOk() {
    Object.keys(this.metaForm.controls).forEach(item => {
      this.metaForm.controls[item].markAsDirty();
      this.metaForm.controls[item].updateValueAndValidity();
    });
    if (this.metaForm.valid) {
      this.modalVisible = false;
      this.submitForm();
    }
  }
  async submitForm() {
    const allRoles = this.metaForm.get('roles').value;
    const roles = [];
    allRoles.forEach(item => {
      if (item.checked) { roles.push(item.value); }
    });
    const cond = {
      group: this.metaForm.get('group').value,
      group_des: this.metaForm.get('group_des').value,
      permission: this.metaForm.get('permission').value,
      permission_des: this.metaForm.get('permission_des').value,
      roles: roles
    };
    const result = await this.net.post('/api/metas', cond);
    if (result) {
      this.nzmsg.success('创建权限成功！');
      this.getMetaList();
    }
  }

  ngOnInit() {
    this.metaForm = this.fb.group({
      group: [null, [Validators.required]],
      group_des: [null, [Validators.required]],
      permission: [null, [Validators.required]],
      permission_des: [null, [Validators.required]],
      roles: [[], [Validators.required]]
    });
  }
}
